#!/bin/bash -x

export PATH=/usr/local/bin:$PATH

KDIR=linux-4.18.0-193

which kpatch-build &>/dev/null
if [ $? -ne 0 ]; then
   echo "kpatch-build is not installed, installing it now ..."
   git clone git@coding.jd.com:jdos_kernel/jdos-kpatch.git
   pushd jdos-kpatch
   make -j$(nproc)
   sudo make install
   popd
fi

if [ -n "${tag}" ]; then
    VER=${tag}
    OLD_TAG=${VER}
    BID=${OLD_TAG##jd_}
    BID=${BID%%_*}
elif [ "$release" = "true" ]; then
	TAG=$(git -C ${KDIR} describe)
	OLD_TAG=${TAG%%-*}
	VER=${OLD_TAG}
    BID=${OLD_TAG##jd_}
else
	TAG=$(git -C ${KDIR} describe HEAD~1)
	OLD_TAG="HEAD~1"
	VER=${TAG//-/_}
    BID=${TAG##jd_}
    BID=${BID%%-*}
fi
PATCH_FILE=$(basename ${branch}).patch


DEBUG_INFO_PATH=${VER}/kernel-debuginfo-4.18.0-193.${dist}.${VER}.x86_64.rpm
VMLINUX=./usr/lib/debug/lib/modules/4.18.0-193.${dist}.${VER}.x86_64/vmlinux
CONFIG=${KDIR}/RPMS/SOURCES/kernel-x86_64.config
EXTRA="--skip-compiler-check"

r=$(echo "$BID >= 020" | bc)
if [ "$r" -ne 1 ]; then
   EXTRA="--skip-compiler-check"
fi

if [ "$builtin" == "true" ]; then
   EXTRA="$EXTRA -t vmlinux"
fi

r=$(echo "$BID >= 011" | bc)
if [ "$r" -ne 1 ]; then
   CONFIG=${KDIR}/configs/kernel-4.18.0-x86_64.config
fi

echo "generating patch file ..."
git -C ${KDIR} diff ${OLD_TAG} > ${PATCH_FILE}

echo "retriving original vmlinux ..."
wget -nv http://storage.jd.local/k8s-node/kernel/${DEBUG_INFO_PATH}
rpm2cpio $(basename ${DEBUG_INFO_PATH}) | cpio -id "*vmlinux"

echo "generating kpatch ko file ..."
git -C ${KDIR} checkout ${OLD_TAG}

extra_ver="-193.${dist}.${VER}.x86_64"
sed -i "s/EXTRAVERSION =/& ${extra_ver}/" linux-4.18.0-193/Makefile
export LOCALVERSION=""
kpatch-build -s ${KDIR} -c ${CONFIG} -j$(nproc) -o . -v ${VMLINUX} ${EXTRA} -R ${PATCH_FILE}

if [ $? -ne 0 ]; then
   echo "kpatch-build error"
   echo
   echo "Error log:"
   cat ~/.kpatch/build.log
   exit 1
fi
